package com.rom.update;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private int process = 0;//当前进度
    private ProgressBar pb_main_download;//进度条
    private TextView tv_show_progress;//进度条

    /**
     * 删除单个文件
     *
     * @param filePath$Name 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    private boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Toast.makeText(getApplicationContext(), "删除历史文件" + filePath$Name + "成功！", Toast.LENGTH_LONG).show();
                return true;
            } else {
                //   Toast.makeText(getApplicationContext(), "删除历史文件" + filePath$Name + "失败！", Toast.LENGTH_LONG).show();
                return false;
            }
        } else {
            // Toast.makeText(getApplicationContext(), "历史文件：" + filePath$Name + "不存在！", Toast.LENGTH_SHORT).show();
            return false;
        }
    }


    /**
     * 下载pdf文件
     *
     * @param context
     * @param url
     */
    private void downLoadROM(Context context, String url) {
        try {
            deleteSingleFile("/sdcard/Download/ocr.zip");
            //使用系统时间命名文件
            String time = String.valueOf(System.currentTimeMillis()).substring(5);
            String subPath = "update.zip";
            /*String subPath = "pdf/invoice" + time + ".pdf";*/
            Uri uri = Uri.parse(url);
            //得到系统的下载管理
            DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            //得到连接请求对象
            DownloadManager.Request requestRom = new DownloadManager.Request(uri);
            //指定在什么网络下允许下载
            requestRom.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
            requestRom.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
            //指定下载文件的保存路径{缓存目录还是sd卡或者手机存储}。注意：用手机自带的文件管理器看不到缓存路径（Android\data\项目包名\files\Download\subPath）
            //  requestRom.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_DOWNLOADS,subPath);
            requestRom.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subPath);
            //requestRom.setDestinationUri(getDownloadPath(context,subPath));
            //表示允许MediaScanner扫描到这个文件，默认不允许
            requestRom.allowScanningByMediaScanner();
            //设置显示下载界面
            requestRom.setVisibleInDownloadsUi(true);
            requestRom.setTitle("rom下载");
            requestRom.setDescription("rom下载");
            //MIME_MapTable是所有文件的后缀名所对应的MIME类型的一个String数组  比如{".apk",    "application/vnd.android.package-archive"},
            requestRom.setMimeType("application/zip");
            // 下载完成后该Notification才会被显示
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
                // Android 3.0版本 以后才有该方法
                //在下载过程中通知栏会一直显示该下载的Notification，在下载完成后该Notification会继续显示，直到用户点击该Notification或者消除该Notification
                requestRom.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            }
            //启动下载,该方法返回系统为当前下载请求分配的一个唯一的ID
            long downLoadId = manager.enqueue(requestRom);

            new Thread(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        try {
                        // 创建一个查询对象
                        DownloadManager.Query query = new DownloadManager.Query();

                        // 根据 下载ID 过滤结果
                        query.setFilterById(downLoadId);

                        // 还可以根据状态过滤结果
// query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);

                    // 执行查询, 返回一个 Cursor (相当于查询数据库)
                        Cursor cursor = manager.query(query);

                        if (!cursor.moveToFirst()) {
                            cursor.close();
                            return;
                        }

                        // 下载ID
                        long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
                        // 下载请求的状态
                        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        // 下载文件在本地保存的路径（Android 7.0 以后 COLUMN_LOCAL_FILENAME 字段被弃用, 需要用 COLUMN_LOCAL_URI 字段来获取本地文件路径的 Uri）
                        String localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        // 已下载的字节大小
                        long downloadedSoFar = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        // 下载文件的总字节大小
                        long totalSize = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                        cursor.close();

                        System.out.println("下载进度: " + downloadedSoFar + "/" + totalSize);

                        /*
                         * 判断是否下载成功，其中状态 status 的值有 5 种:
                         *     DownloadManager.STATUS_SUCCESSFUL:   下载成功
                         *     DownloadManager.STATUS_FAILED:       下载失败
                         *     DownloadManager.STATUS_PENDING:      等待下载
                         *     DownloadManager.STATUS_RUNNING:      正在下载
                         *     DownloadManager.STATUS_PAUSED:       下载暂停
                         */
                        if (status == DownloadManager.STATUS_SUCCESSFUL) {
                            /*
                             * 特别注意: 查询获取到的 localFilename 才是下载文件真正的保存路径，在创建
                             * 请求时设置的保存路径不一定是最终的保存路径，因为当设置的路径已是存在的文件时，
                             * 下载器会自动重命名保存路径，例如: .../demo-1.apk, .../demo-2.apk
                             */
                            System.out.println("下载成功, 打开文件, 文件路径: " + localFilename);
                            break;
                        }
                        if (status == DownloadManager.STATUS_RUNNING) {
                            Log.e("--sss--Method--", "status" + status +  "下载进度: " + downloadedSoFar + "/" + totalSize);
                            mMainHandler.post(() -> {
                             //   tv_main_desc.setText("下载进度: " + downloadedSoFar + "/" + totalSize);//显示当前进度为多少
                                //Toast.makeText(getApplicationContext(), "文件md5正确" , Toast.LENGTH_LONG).show();
                            });
                        }


                            Thread.sleep(1000);
                            Log.e("--sss--Method--", "status" + status +  "下载进度: " + downloadedSoFar + "/" + totalSize);
                        } catch (Exception ee) {
                            ee.printStackTrace();
                    }


                    }
                }
            }).start();

        } catch (Exception e) {
            Uri uri = Uri.parse(url);
            //String android.intent.action.VIEW 比较通用，会根据用户的数据类型打开相应的Activity。如:浏览器,电话,播放器,地图
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }
    long downloadId=0;
    private void Download() {


//
//        String PIC_URL = "http://pic11.nipic.com/20101119/3320946_221711832717_2.jpg";
//        String apk_url="http://192.168.1.166:8080/apk/termux.apk";
//        String rom_url="http://192.168.1.166:8080/apk/update.zip";
//        String URL="https://qdcu02.baidupcs.com/file/6e1780ec8mf213062d04c2be16dc5b22?bkt=en-713b21d6dbc3139895cc3f4f5a71dd15a1bdffd2d31d2aa831519e97eab063694248de3981bb0698e34febb6724ee5fc0e9930b58608939ddf2e62d74631ca2c&fid=3523780425-250528-740767389332003&time=1612780537&sign=FDTAXUGERQlBHSKfWqi-DCb740ccc5511e5e8fedcff06b081203-EYtuPD%2B297VQPNrh0zW0xZXWCq4%3D&to=66&size=7339527&sta_dx=7339527&sta_cs=772&sta_ft=mp3&sta_ct=7&sta_mt=6&fm2=MH%2CYangquan%2CAnywhere%2C%2Cliaoning%2Ccnc&ctime=1579765258&mtime=1581860682&resv0=-1&resv1=0&resv2=rlim&resv3=5&resv4=7339527&vuk=3523780425&iv=2&htype=&randtype=&newver=1&newfm=1&secfm=1&flow_ver=3&pkey=en-8e224f0ebe23d5003f9eac83b25192898088b25ae9672dc801cfa531e7a127e5fd9f4ae6352c7c2a137ffa61ac439d78703ec411286d2a27305a5e1275657320&expires=8h&rt=sh&r=679582431&vbdid=4099658927&fin=1507.mp3&fn=1507.mp3&rtype=1&clienttype=0&dp-logid=899295557006295793&dp-callid=0.1&hps=1&tsl=0&csl=0&fsl=-1&csign=xWZ41LgmCcNQ0q0Dsh90CV0p64E%3D&so=0&ut=1&uter=4&serv=0&uc=914015225&ti=068bcab50ae430c7b58c65f15a0944a5f9dfed46f277664e&hflag=30&from_type=3&adg=c_471506f3e299e981d5ff3907c7f6a140&reqlabel=250528_f_18880eb0b26fb28a1a4dc93acbd24450_-1_35d079bf70f7dedb92cd2142ed6d43a9&by=themis";
//        //downloadUtils.downloadAPK("http://192.168.1.166:8080/apk/t.mp3", "t.mp3");
//        //  downloadUtils.downloadAPK("http://192.168.1.166:8080/apk/termux.apk", "termux.apk");
//          downloadUtils.downloadAPK(rom_url, "update.zip");
        EditText text_url = (EditText) findViewById(R.id.edit_rom_url);
        String rom_url = text_url.getText().toString().trim();
        if (rom_url.isEmpty() || rom_url.indexOf("http") == -1)                                  //判断IP输入框是否为空
        {
            Toast.makeText(MainActivity.this, "请输入正确的下载地址", Toast.LENGTH_LONG).show();
        } else {
            deleteSingleFile("/sdcard/Download/update.zip");
            final HttpDownloader httpDownloader = new HttpDownloader();

            final String urlStr = "http://10.10.10.11/e%3A/x820%E4%B9%90%E8%A7%86%E5%88%B7%E6%9C%BA/x820/rom_ota/update.zip";
            final String path = "/Download/";
            final String fileName = "update.zip";

            FileUtils.reset();
            // 文件的上传下载操作，请务必放在新开启的线程中
            new Thread(new Runnable() {
                @Override
                public void run() {
                    httpDownloader.downFile(urlStr, path, fileName);
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                        }
                    });
                }

            }).start();
            long begin_time=System.currentTimeMillis();
            new Thread(new Runnable() {
                @Override
                public void run() {//
                    while (FileUtils.state==0) {
                        try {
//                            //process += 5;
//                            if (process >= 100) process = 100;
                            mMainHandler.post(() -> {
                                if(FileUtils.file_totalsize!=0)
                                process=(int)( FileUtils.current_totalCount*100/FileUtils.file_totalsize);
                                pb_main_download.setProgress(process);
                                tv_show_progress.setText(FileUtils.currentMB + "MB " +process +"% 用时："+(System.currentTimeMillis()-begin_time)/1000 +"秒");//显示当前进度为多少
                            });
                            Log.e("syz",  FileUtils.currentMB + "MB");
                            Thread.sleep(500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    mMainHandler.post(() -> {
                        if(FileUtils.state==FileUtils.STATE_DOWNLOAD_OK) {
                            pb_main_download.setProgress(100);
                            tv_show_progress.setText("下载完成:" + FileUtils.currentMB + "MB 100% 用时：" + (System.currentTimeMillis() - begin_time) / 1000 + "秒");//显示当前进度为多少
                        }
                        if(FileUtils.state==FileUtils.STATE_DOWNLOAD_ERROR) {
                            pb_main_download.setProgress(0);
                            tv_show_progress.setText("下载异常:" + FileUtils.currentMB + "MB 100% 用时：" + (System.currentTimeMillis() - begin_time) / 1000 + "秒");//显示当前进度为多少
                        }
                    });

                }
            }).start();
//            DownloadManagerUtil dm = new DownloadManagerUtil((Context)MainActivity.this);
//            if (dm.checkDownloadManagerEnable()) {
////                if (MyApplication.Companion.getDownloadId() != 0L) {
////                    dm.clearCurrentTask(MyApplication.Companion.getDownloadId());
////                }
//              downloadId = dm.download(rom_url, "下载", "下载");
////                MyApplication.Companion.setDownloadId(dm.download(MainActivity.this.url, MainActivity.this.title, MainActivity.this.desc));
//            } else {
//                Toast.makeText((Context)MainActivity.this, (CharSequence)"请开启下载管理器", 0).show();
//            }
            //downloadUtils =   new DownloadUtils(MainActivity.this);
            //downloadUtils.downloadAPK("http://35-android-eq.oss-cn-hangzhou.aliyuncs.com/MEQ.apk", "MEQ.zpk");
            //downloadUtils.downloadAPK("http://192.168.2.4/E%3A/ocr.zip", "ocr.zip");
            //将原有rom清除
//            deleteSingleFile("/sdcard/Download/update.zip");
//            Intent intent = new Intent();
//            intent.setAction("android.intent.action.VIEW");
//            Uri content_url = Uri.parse(rom_url);
//            intent.setData(content_url);
//            this.startActivity(intent);

          // downLoadROM(getApplicationContext(), rom_url);
        }

    }

    public void button_download_onClick(View view) {
        //TODO 这里面放所需要执行的程序代码
        Download();

    }
    public void button_download_local_onClick(View view) {
        deleteSingleFile("/sdcard/Download/ocr.zip");
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        //Uri content_url = Uri.parse("http://10.10.10.11/D%3A/%E8%81%94%E6%83%B3LeezP710/%E5%9B%BA%E4%BB%B6/webuild/android7%20update%20package/update.zip");
        Uri content_url = Uri.parse("http://192.168.2.5/E%3A/ocr.zip");
        intent.setData(content_url);
        this.startActivity(intent);
      //  downLoadROM(getApplicationContext(), " http://10.10.10.11/e%3A/x820%E4%B9%90%E8%A7%86%E5%88%B7%E6%9C%BA/x820/rom_ota/update.zip".trim());

    }
    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();


    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(toHexString(MD5.digest())).toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String toHexString(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    public static int STATE_INIT = 0;
    public static int STATE_MD5_OK = 1;
    public static int STATE_MD5_ERROR = 2;
    public static int STATE_FILE_MISSING = 3;

    private int checkRomfile(String filePath$Name) {
        File file = new File(filePath$Name);
        String strFilesize = Long.toString(file.length());
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        // 校验串是 文件大小+md5(文件内容）
        // 6713785508f24d5eb9f6e950b7b87bdef69ce6dd2
        if (file.exists() && file.isFile() && file.length() > 500000000L) {
            EditText text_md5 = (EditText) findViewById(R.id.edit_md5);
            String strmd5 = text_md5.getText().toString().trim();
            String str_romfilemd5 = getMD5(file);
            //if (strmd5.indexOf(str_romfilemd5) != -1 && strmd5.indexOf(strFilesize) != -1) {
            if (str_romfilemd5.indexOf(strmd5) != -1 ) {
                //   Toast.makeText(getApplicationContext(), "检测ROM文件" + filePath$Name + "成功！大小" + file.length() + " md5:" + str_romfilemd5, Toast.LENGTH_LONG).show();
                Log.e("--sss--Method--", "检测ROM文件" + filePath$Name + "成功！大小" + file.length() + " md5:" + str_romfilemd5);
                return STATE_MD5_OK;
            } else {
                //  Toast.makeText(getApplicationContext(), "ROM文件" + filePath$Name + "不符合要求，大小" + file.length() + " md5:" + str_romfilemd5 +"要求："+strmd5, Toast.LENGTH_LONG).show();

                Log.e("--sss--Method--", "检测ROM文件" + filePath$Name + "失败 md5:" + str_romfilemd5 +"设定md5 "+strmd5+ " 大小" + file.length() );
                return STATE_MD5_ERROR;
            }

        } else {
            // Toast.makeText(getApplicationContext(), "error 2,检测ROM文件：" + filePath$Name + "不存在！", Toast.LENGTH_LONG).show();
            return STATE_FILE_MISSING;
        }
    }

    private static Handler mMainHandler = new Handler(Looper.getMainLooper());
    public void update_rom(String path)
    {
        //TODO 这里面放所需要执行的程序代码
//        if(checkRomfile("/sdcard/Download/update.zip")==true)
//        {
//                Toast.makeText(getApplicationContext(), "文件md5正确" , Toast.LENGTH_LONG).show();
//                startActivity(new Intent(getApplicationContext(), OtaUpgradeNotifyActivity.class));
//
//        }
        Toast.makeText(getApplicationContext(), "检测文件md5", Toast.LENGTH_LONG).show();
        //startActivity(new Intent(MainActivity.this, OtaUpgradeNotifyActivity.class));
        final int[] checkresult = {STATE_INIT};
        new Thread(new Runnable() {
            @Override
            public void run() {//
                checkresult[0] = checkRomfile(path);
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    if (checkresult[0] != STATE_INIT) {
                        mMainHandler.post(() -> {
                            process = 100;
                            pb_main_download.setProgress(process);
                        });
                        break;
                    } else {
                        try {
                            process += 5;
                            if (process >= 100) process = 100;
                            mMainHandler.post(() -> {
                                pb_main_download.setProgress(process);
                                tv_show_progress.setText(process + "%");//显示当前进度为多少
                            });
                            Log.e("syz", "check state " + checkresult[0]);
                            Thread.sleep(500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
                try {
                    if (checkresult[0] == STATE_MD5_OK) {

                        Log.e("syz", "check 检测文件md5 成功 " + checkresult[0]);
                        //MyToast.showOnUIThreadx(getApplicationContext(), "检测文件md5 成功", Toast.LENGTH_LONG);
                        Log.e("syz", "check startActivity begin " + checkresult[0]);
                        mMainHandler.post(() -> {
                            tv_show_progress.setText("100%,校验文件md5 成功");//显示当前进度为多少
                            //Toast.makeText(getApplicationContext(), "文件md5正确" , Toast.LENGTH_LONG).show();
                            startActivity(new Intent(getApplicationContext(), OtaUpgradeNotifyActivity.class));
                        });
                    } else if (checkresult[0] == STATE_FILE_MISSING) {
                        process = 0;
                        pb_main_download.setProgress(process);

                        Log.e("syz", "check md5校验失败 成功 " + checkresult[0]);
                        mMainHandler.post(() -> {
                            tv_show_progress.setText("update.zip不存在,请重新下载");//显示当前进度为多少
                            //Toast.makeText(getApplicationContext(), "update.zip不存在" , Toast.LENGTH_LONG).show();
                        });
                    } else if (checkresult[0] == STATE_MD5_ERROR) {
                        process = 0;
                        pb_main_download.setProgress(process);
                        Log.e("syz", "check md5校验失败 " + checkresult[0]);

                        mMainHandler.post(() -> {
                            tv_show_progress.setText("update.zip md5校验失败");//显示当前进度为多少
                            // Toast.makeText(getApplicationContext(), "md5校验失败" , Toast.LENGTH_LONG).show();
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        if(checkresult[0] ==1)
//        {
//            mMainHandler.post(() -> {
//                Toast.makeText(getApplicationContext(), "文件md5正确" , Toast.LENGTH_LONG).show();
//                startActivity(new Intent(getApplicationContext(), OtaUpgradeNotifyActivity.class));
//            });
//        }
    }
    public void button_update_onClick(View view) {
        update_rom("/sdcard/Download/update.zip");
    }

    public void button_local_update_onClick(View view) {
        //TODO 这里面放所需要执行的程序代码
        try {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            // 所有类型
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                startActivityForResult(Intent.createChooser(intent, "请选择文件"), 1);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
            }
            Toast.makeText(MainActivity.this, "button_local_update_onClick~", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {

        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            //Get the Uri of the selected file
            Uri uri = data.getData();
            Log.i("filepath", " = " + uri.getPath());
            if (null != uri) {
                String path = ContentUriUtil.getPath(this, uri);
                Log.i("filepath", " = " + path);
                updateFilePath(path);
            }
        }
    }

    private void updateFilePath(final String path) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EditText edit_rom_url = (EditText) findViewById(R.id.edit_rom_url);
                edit_rom_url.setText(path);
                update_rom(path);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        permissionRequest();
        //根据ID找到进度条
        pb_main_download = findViewById(R.id.pb_main_download);
        tv_show_progress = findViewById(R.id.tv_show_progress);
    }

    /**
     * 获取用户权限
     */
    private void permissionRequest() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.READ_CALENDAR,
                    Manifest.permission.WRITE_CALENDAR,
                    Manifest.permission.INTERNET,
            };

            List<String> mPermissionList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }

            if (mPermissionList.isEmpty()) {// 全部允许
                // toMain(); //执行下一步操作
            } else {//存在未允许的权限
                String[] mPermissions = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(MainActivity.this, mPermissions, 1001);
            }
        }
    }
}